//
//  KAAddAccountViewController.m
//  KeepAccount
//
//  Created by Veer on 2017/12/19.
//  Copyright © 2017年 Veer. All rights reserved.
//

#import "KAAddAccountViewController.h"

#import "XDropMenuView.h"
#import "KAAddAccountCollectionCell.h"
#import "QHKeyboard.h"
#import "KeyboardToolbar.h"
#import "VRChooseDateView.h"

#import "KACategoryModel.h"
#import "KAAccountModel.h"


static CGFloat itemW = 55;
static CGFloat itemH = 80;
static NSInteger itemCount = 4;

@interface KAAddAccountViewController () <XDropMenuViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, QHKeyboardDelegate>

@property (nonatomic, weak) UICollectionView *collectionView;

@property (nonatomic, strong) QHKeyboard *keyBoard;
@property (nonatomic, strong) KeyboardToolbar *keyboardToolBar;
@property (nonatomic, strong) VRChooseDateView *chooseDateView;

@property (nonatomic, strong) NSMutableArray<KACategoryModel *> *categoryModelArray;

@property (nonatomic, assign) NSInteger type;

@end

@implementation KAAddAccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.categoryModelArray = [NSMutableArray array];

    [self setupNav];
    [self setupSubView];
    [self setupDropMenu];
    
    self.keyboardToolBar = [KeyboardToolbar keyboardToolbar];
    self.keyBoard = [[QHKeyboard alloc] init];
    self.keyBoard.delegate = self;
    self.keyBoard.toolBar = self.keyboardToolBar;
    self.keyBoard.responderLable = self.keyboardToolBar;
    
    [self getDataWithType:0];
    
    if (self.curAccountModel) {
        [self loadDefaultData];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (self.curAccountModel) {
        NSInteger index = self.curAccountModel.categoryModel.sortnum - 1;
        [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    }
}

- (void)setupNav
{
    
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [shareBtn setImage:[UIImage imageNamed:@"share_button_image"] forState:UIControlStateNormal];
    [shareBtn setTitle:@"取消" forState:UIControlStateNormal];
    [shareBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    shareBtn.titleLabel.font = VRFont(16);
    shareBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [shareBtn addTarget:self action:@selector(cancelClick:) forControlEvents:UIControlEventTouchUpInside];
    shareBtn.frame = CGRectMake(0, 0, 70, 18);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:shareBtn];
    
    if (self.navigationController.childViewControllers.count > 1) {
        
        self.fd_interactivePopDisabled = YES;
        self.navigationItem.leftBarButtonItem.customView.hidden = YES;
    }
}


- (void)setupSubView
{
    
    CGFloat margin = (SCREEN_WIDTH - itemW * itemCount) / (itemCount + 1);
    
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = margin;
    layout.minimumLineSpacing = 20;
    layout.sectionInset = UIEdgeInsetsMake(20, margin, 0, margin);
//    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.itemSize = CGSizeMake(itemW, itemH);
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.alwaysBounceVertical = YES;
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    
    //3.注册collectionViewCell
    //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
    [collectionView registerClass:[KAAddAccountCollectionCell class] forCellWithReuseIdentifier:@"cellId"];
    
    //注册headerView  此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致  均为reusableView
    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView"];
    
    self.chooseDateView = [[VRChooseDateView alloc] init];
    WeakSelf(weakSelf)
    self.chooseDateView.sureBlock = ^(NSDate *date) {
        
        weakSelf.keyBoard.date = date;
    };
}


- (void)setupDropMenu
{
    
    //若列表展示内容与按钮展示内容相同则showArr传nil即可。
    XMenuModel *model0 = [[XMenuModel alloc] init];
    model0.name = @"支出";
    model0.imageName = @"ic_expenses";
    
    XMenuModel *model1 = [[XMenuModel alloc] init];
    model1.name = @"收入";
    model1.imageName = @"ic_income";
    NSMutableArray *totalArray = [NSMutableArray array];
    [totalArray addObject:@[model0, model1]];

    XDropMenuView *dropMenu = [[XDropMenuView alloc] initWithFrame:CGRectMake(70, 0, SCREEN_WIDTH - 70 * 2, 36) showOnView:self.view AllDataArr:totalArray showArr:[@[@"支出"] mutableCopy]];
    dropMenu.buttonNormalImage = @"pull_down_selector_normal";
    dropMenu.buttonSelectedImage = @"pull_down_selector_normal";
    dropMenu.fonteSize = 18;
    [dropMenu selectClum:0 Row:0];
    dropMenu.delegate = self;
    self.navigationItem.titleView = dropMenu;
}


- (void)loadDefaultData

{
    
    KACategoryModel *curCategoryModel = nil;
    for (int i = 0; i < self.categoryModelArray.count; i++){
        
        KACategoryModel *categoryModel = self.categoryModelArray[i];
        if (self.curAccountModel.categoryModel.id == categoryModel.id) {
            
            curCategoryModel = categoryModel;
        }
    }
    
    NSInteger index = self.curAccountModel.categoryModel.sortnum - 1;
    [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    
    [self.keyBoard showOnView:self.view];
    self.keyboardToolBar.note = self.curAccountModel.note;
    self.keyboardToolBar.text = [NSString stringWithFormat:@"%lf", self.curAccountModel.money];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    self.keyBoard.date = [formatter dateFromString:self.curAccountModel.date];
}


#pragma mark - data
- (void)getDataWithType:(NSInteger)type
{
    self.categoryModelArray = [[KADataBase sharedDataBase] getCategoryModelWithType:type];
    [self.collectionView reloadData];
}

#pragma mark - action
- (void)cancelClick:(UIButton *)sender
{
    if (self.navigationController.childViewControllers.count > 1) {
        
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
}


#pragma mark collectionView代理方法
//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.categoryModelArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    KACategoryModel *model = self.categoryModelArray[indexPath.row];
    
    KAAddAccountCollectionCell *cell = (KAAddAccountCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"cellId" forIndexPath:indexPath];
    cell.model = model;
    
    return cell;
}

//通过设置SupplementaryViewOfKind 来设置头部或者底部的view，其中 ReuseIdentifier 的值必须和 注册是填写的一致，本例都为 “reusableView”
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView" forIndexPath:indexPath];
    headerView.backgroundColor =[UIColor grayColor];
    UILabel *label = [[UILabel alloc] initWithFrame:headerView.bounds];
    label.text = @"这是collectionView的头部";
    label.font = [UIFont systemFontOfSize:20];
    [headerView addSubview:label];
    return headerView;
}

//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

    if (!self.keyBoard.isShow) {
        [self.keyBoard showOnView:self.view];
    }
    
    KACategoryModel *model = self.categoryModelArray[indexPath.row];

}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.keyBoard dissmiss];
}


#pragma mark - XDropMenuViewDelegate
- (void)dropMenuView:(XDropMenuView *)dropMenuView didSelectRowAtColum:(NSInteger)colum Row:(NSInteger)row model:(XMenuModel *)model
{
    [self.keyBoard dissmiss];
    self.type = row;
    [self getDataWithType:row];
}

#pragma mark - QHKeyboardDelegate
- (void)keyboardDoneDidClickedWith:(QHKeyboard *)keyboard
{
    
    NSString *noteStr = self.keyboardToolBar.noteTF.text;
    double amount = [self.keyboardToolBar.text doubleValue];
    if (amount == 0) {
        return;
    }
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSString *dateStr = [formatter stringFromDate:self.keyBoard.date];
    
    NSIndexPath *curIndexPath = [[self.collectionView indexPathsForSelectedItems] lastObject];
    KACategoryModel *categoryModel = self.categoryModelArray[curIndexPath.row];
    
    if (self.curAccountModel) {
        
        self.curAccountModel.date = dateStr;
        self.curAccountModel.money = amount;
        self.curAccountModel.type = self.type;
        self.curAccountModel.categoryid = categoryModel.id;
        self.curAccountModel.note = noteStr;
        
        self.curAccountModel.categoryModel = categoryModel;
        
        [[KADataBase sharedDataBase] updateAccount:self.curAccountModel];
    }else{
        
        KAAccountModel *accountModel = [[KAAccountModel alloc] init];
        accountModel.date = dateStr;
        accountModel.money = amount;
        accountModel.type = self.type;
        accountModel.categoryid = categoryModel.id;
        accountModel.note = noteStr;
        
        [[KADataBase sharedDataBase] addAccountModel:accountModel];
    }
    
    // 修改徽章数据
    [[KADataBase sharedDataBase] updateBadgeWithType:2];
    [[KADataBase sharedDataBase] updateBadgeWithType:3];
    
    
    if (self.addCountFinishedBlock) {
        self.addCountFinishedBlock();
    }
    
    // 发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:kAddAccountNotificationName object:self];
    if (self.navigationController.childViewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
}


- (void)keyboardDateDidClickedWith:(QHKeyboard *)keyboard
{
    
    self.chooseDateView.date = keyboard.date;
    [self.chooseDateView showOnWindow];
}


- (void)dealloc
{
    NSLog(@"delloc_KAAddAccountViewController");
//    [self.keyBoard removeFromSuperview];
}



@end
